<template>
	<view class="home">
		<u-sticky offset-top="0">
			<view class="tophead">
				<uni-icons type="left" color="#666" size="26" @click="retFn"></uni-icons>

				<view class="" style="width: 100rpx;display: flex;justify-content: flex-end;">
					<view class="" style="margin-right: 20rpx;">
						<uni-icons type="gear-filled" color="#666" size="26" @click="allocationFn"></uni-icons>
					</view>
					<uni-icons type="calendar" color="#666" size="26" @click="flowHistoryFn"></uni-icons>
				</view>
			</view>
		</u-sticky>
		<!-- 内容 -->
		<view class="" style="margin: 30rpx 50rpx;"> 
			<u-button class="butto" @click="errorEliminationFn" type="warning" shape="circle" text="清除报警"></u-button>
		</view>
		<view class="emergencySuspension">
			<u-button class="butto" @click="stopmodalFn" type="error" shape="circle" text="紧急暂停"></u-button>
			<u-button class="butto" @click="stopzeroinglFn" type="success" shape="circle" text="手动归位"></u-button>
		</view>
		<view class="concent_box">

			<view class="inibox">
				<view class="inibox_but" hover-class="inibox_acv" @click="iniIFFn">
					设备初始化
				</view>
				<!-- 				<view class="inibox_but" hover-class="inibox_acv" @tap="$u.debounce(iniFn, 300)">
					设备初始化
				</view> -->
			</view>
			<view class="butt_box">
				<view class="butt_i" v-for="(i,index) in cezhanObj.cexianlist" :key="index">
					<u-button @click="cexianBUTT(i,index)" :color="i.color" type="primary" :text="index + 1"></u-button>
				</view>
			</view>
			<view class="yuan">
				<view class="yuan_a1" hover-class="yuan_a_av1" @tap="$u.debounce(inwaterFn, 300)"
					:style="{ pointerEvents: pointerWater}">
					<view class="text">
						设备
					</view>
					<view class="text">
						入水
					</view>
				</view>
				<view class="yuan_a2" hover-class="yuan_a_av2" @tap="$u.debounce(inquiryFn, 300)"
					:style="{ pointerEvents: pointerMeasure}">
					<view class="text">
						开始
					</view>
					<view class="text">
						测量
					</view>
				</view>
			</view>
			<!-- <button @click="delallFn()">清空</button> -->
			<view class="realtime">
				<view class="i_a" style="color: #dd5e04;">
					当前水深：
				</view>
				<view class="i_b" style="color: #ff6923;">
					{{wD}}
				</view>
			</view>
			<view class="realtime">
				<view class="i_a" style="color: #00aa7f;">
					瞬时流速：
				</view>
				<view class="i_b">
					{{timereal}}
				</view>
			</view>
			<!-- 图表 -->
			<view class="ucharts_box">
				<celiucheucharts ref="myclc" :listobjCLC="objCLC"></celiucheucharts>
			</view>
			<view class="box_num">
				<view class="num_i" v-for="(i,index) in sumArr" :key="index">
					<view class="text_top">
						<view class="text">
							<view class="text_a">
								测线流速：
							</view>
							<view class="text_b">
								{{i.aveTy}}
							</view>
						</view>
					</view>
					<view class="text_bom">
						{{index + 1}}号测线
					</view>
				</view>
			</view>
			<view class="realtime">
				<view class="i_a" style="color: #00557f;">
					渠道流量：
				</view>
				<view class="i_b" style="color: #0adfff;">
					{{liusliangnub}}
				</view>
				<view class="i_c">m³/s</view>
			</view>
			<view class="" style="margin: 20rpx;">
				<u-button @click="preserveFn" :disabled="disabledIf" type="warning" shape="circle"
					text="保存数据"></u-button>
			</view>
		</view>
		<!-- 弹出弹出层 -->
		<u-popup :show="showpop" mode="left">
			<view class="classpop">
				<view class="conpop">
					<view class="popitem">
						<uni-data-select placeholder="请选择测线数量" v-model="valuesel" :clear="false" :localdata="rangesel"
							@change="changesel"></uni-data-select>
					</view>
					<view class="popitem" v-for="(i,index) in cezhanObj.cexianlist" :key="index">
						<u-input clearable placeholder="输入测线位置" type="number" v-model="i.cR">
							<u--text text="米" slot="suffix" margin="0 3px 0 0" type="tips"></u--text>
						</u-input>
						<view class="l">
							<u--input clearable type="number" placeholder="输入系数" border="surround"
								v-model="i.vM"></u--input>
						</view>
					</view>
					<view class="popitem">
						<view class="poptext">
							安装高度：
						</view>
						<u--input clearable type="number" placeholder="输入安装高度" border="surround"
							v-model="cezhanObj.installH"></u--input>
					</view>
					<view class="popitem">
						<view class="poptext">
							探头入水深度：
						</view>
						<u--input clearable type="number" placeholder="输入探头入水深度" border="surround"
							v-model="cezhanObj.thoroughH"></u--input>
					</view>
					<view class="popitem">
						<view class="poptext">
							距离水面高度：
						</view>
						<u--input clearable type="number" placeholder="输入距离水面高度" border="surround"
							v-model="cezhanObj.waterH"></u--input>
					</view>
					<view class="popitem">
						<view class="poptext">
							左坡角度：
						</view>
						<u--input clearable type="number" placeholder="左坡角度" border="surround"
							v-model="cezhanObj.lSA"></u--input>
						<view class="" style="width: 120rpx;margin-left: 15rpx;">
							<u--input clearable type="number" placeholder="系数" border="surround"
								v-model="cezhanObj.kL"></u--input>
						</view>
					</view>
					<view class="popitem">
						<view class="poptext">
							右坡角度：
						</view>
						<u--input clearable type="number" placeholder="右坡角度" border="surround"
							v-model="cezhanObj.rSA"></u--input>
						<view class="" style="width: 120rpx;margin-left: 15rpx;">
							<u--input clearable type="number" placeholder="系数" border="surround"
								v-model="cezhanObj.kR"></u--input>
						</view>
					</view>
					<view class="popitem">
						<view class="poptext">
							起始测线系数：
						</view>
						<u--input clearable type="number" placeholder="起始测线系数" border="surround"
							v-model="cezhanObj.vmL"></u--input>
					</view>
					<view class="popitem">
						<view class="poptext">
							结束测线系数：
						</view>
						<u--input clearable type="number" placeholder="起始测线系数" border="surround"
							v-model="cezhanObj.vmR"></u--input>
					</view>
					<view class="popitem">
						<view class="poptext">
							渠底宽度：
						</view>
						<u--input clearable type="number" placeholder="输入渠底宽度" border="surround"
							v-model="cezhanObj.qudikuandu"></u--input>
					</view>
				</view>
			</view>
			<view class="butpop">
				<!-- <u-button @click="cancelFn" text="取消"></u-button> -->
				<view class="" style="padding: 30rpx;">
					<u-button @click="confirmFn" type="success" text="确定"></u-button>
				</view>

			</view>
		</u-popup>
		<!-- 保存历史数据弹窗 -->
		<u-popup :show="flowHistorypop" mode="left">
			<view class="pop_istoryFn" style="background-color: #dcdddf;">
				<view class="conpop" v-for="(i,index) in Arrflow" :key="index" @longpress="onLongPress(i)"
					@click="flowCheckpopFn(i)">
					<view class="popitem">
						<view class="poptext" style="color: #6088b9;">
							测量时间：
						</view>
						<view class="poptext_b" style="color: #000000;">
							{{i.time}}
						</view>
					</view>
					<view class="popitem">
						<view class="poptext" style="color: #6088b9;">
							测线条数：
						</view>
						<view class="poptext_c">
							{{i.sumArr.length}}
						</view>
					</view>
					<view class="popitem">
						<view class="poptext" style="color: #6088b9;">
							渠道流量：
						</view>
						<view class="poptext_c">
							{{i.liusliangnub}}
						</view>
					</view>
				</view>
			</view>
			<view class="butflx" style="background-color: #dcdddf">
				<u-button @click="confirmHistoryFn" type="success" text="返回"></u-button>
			</view>
		</u-popup>
		<!-- 查看历史数据 -->
		<u-popup :show="flowCheckpop" mode="top">
			<view class="viewHistory">
				<view class="realtime">
					<view class="" style="color: #4a4a4a;">
						测量时间：
					</view>
					<view class="" style="color: #2f4b5a;">
						{{letviewHistory.time}}
					</view>
				</view>
				<view class="realtime">
					<view class="i_a" style="color: #dd5e04;">
						水深：
					</view>
					<view class="i_b" style="color: #ff6923;">
						{{letviewHistory.wD}}
					</view>
				</view>
				<view class="box_num">
					<view class="num_i" v-for="(i,index) in letviewHistory.sumArr" :key="index">
						<view class="text_top">
							<view class="text">
								<view class="text_a">
									测线流速：
								</view>
								<view class="text_b">
									{{i.aveTy}}
								</view>
							</view>
						</view>
						<view class="text_bom">
							{{index + 1}}号测线
						</view>
					</view>
				</view>
				<view class="realtime">
					<view class="i_a" style="color: #00557f;">
						渠道流量：
					</view>
					<view class="i_b" style="color: #0adfff;">
						{{letviewHistory.liusliangnub}}
					</view>
					<view class="i_c">m³/s</view>
				</view>
			</view>
			<view class="butflx">
				<u-button @click="confirmflowCheckpopFn" type="warning" text="返回" shape="circle"></u-button>
			</view>
		</u-popup>
		<!-- 查看历史数据 -->
		<!-- 是否删除 -->
		<u-modal :show="showHistoryIF" confirmColor="#ff4c55" title="是否删除数据" @confirm="confirmHistoryIF"
			@cancel="cancelHistoryIF" showCancelButton></u-modal>
		<!-- 是否返回 -->
		<u-modal :show="showIF" :title="titleIF" @confirm="confirmIF" @cancel="cancelIF" showCancelButton></u-modal>
		<!-- 初始化电机 -->
		<u-modal :show="infIF" title="初始化设备" @confirm="cinfconfirmIF" @cancel="infcancelIF" showCancelButton></u-modal>
		<u-modal :show="stopIF" title="紧急暂停" @confirm="cinfstopIFIF" @cancel="stopstopIFIF" showCancelButton></u-modal>
		<u-modal :show="zeroingstopIF" title="手动归位" @confirm="cinfzeroingIFIF" @cancel="stopzeroingIFIF"
			showCancelButton></u-modal>
		<!-- <button @click="continuityFn">测试</button> -->
	</view>
</template>

<script>
	import celiucheucharts from '@/pages/home/measuringflow/celiucheUcharTS.vue'
	import dayjs from '@/common/dayjs.min.js'
	export default {
		components: {
			celiucheucharts
		},
		data() {
			return {
				stopIF: false,
				zeroingstopIF: false,
				infIF: false,
				objCLC: {
					categories: [],
					series: [{
						data: []
					}],
				},
				letviewHistory: {}, //查看历史
				flowCheckpop: false,
				Arrflow: [], //历史记录
				disabledIf: true,
				urlAlphabet: 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict',
				deleteId: null,
				flowHistorypop: false,
				inidev: true,
				liusliangnub: 0, //平均总流量
				timereal: 0, //实时数据
				pointerWater: 'auto',
				pointerMeasure: 'auto',
				showHistoryIF: false,
				showIF: false,
				titleIF: '是否返回',
				cezhanObj: {
					installH: '4.3',
					thoroughH: '0.25',
					waterH: '0.5',
					lSA: '26.5', //左坡脚
					rSA: '26.5', //右坡角
					kL: '1', //左坡系数
					kR: '1', //右坡系数
					qudikuandu: '14', //渠底宽度
					vmL: '1', //起始测线系数
					vmR: '1', //结束测线系数
					cexianlist: [], // 测线坐标和系数
				},
				valuesel: 0,
				rangesel: [{
						value: 3,
						text: "测线3"
					},
					{
						value: 4,
						text: "测线4"
					},
					{
						value: 5,
						text: "测线5"
					},
					{
						value: 6,
						text: "测线6"
					},
					{
						value: 7,
						text: "测线7"
					},
					{
						value: 8,
						text: "测线8"
					},
					{
						value: 9,
						text: "测线9"
					},
				],
				setUp: {},
				showpop: false,
				deviceId: '', //蓝牙
				serviceId: '', //蓝牙
				characteristicId: '', //蓝牙
				fff: '', //蓝牙
				mfvNumArr: [], //获取流速
				sumArr: [], //求平均流速
				sumIfArr: true, //判断平均和数组
				timerFn: 0, //计时次数
				wD: 0, //水深
				count: 0, //计数
				depthWater: [] //水深
			}
		},
		onShow() {
			this.deviceId = this.vuex_deviceId
			this.getBLEDeviceServices()
		},
		onLoad(option) {
			// 图表
			setTimeout(() => {
				this.$refs.myclc.onloshow()
			}, 1000)
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			uni.showLoading({
				mask: true,
				title: '获取服务中...'
			});
			setTimeout(() => {
				uni.hideLoading()
			}, 3000)
		},
		methods: {
			// 清空
			delallFn() {
				this.timereal = 0
				this.sumArr = []
				this.liusliangnub = 0
				this.disabledIf = true
			},
			// 手动归位
			stopzeroinglFn() {
				this.zeroingstopIF = true
			},
			cinfzeroingIFIF() {
				this.zeroingFn()
				this.zeroingstopIF = false
			},
			stopzeroingIFIF() {
				this.zeroingstopIF = false
			},
			// 手动归位
			zeroingFn() {
				this.yWalkFn()
				setTimeout(() => {
					this.xWalkFn()
				}, 3000)
			},
			// 消除报错
			errorEliminationFn() {
				let str = ['0x01', '0x06', '0x20', '0x0E', '0x00', '0x06', '0xCB', '0x63']
				this.conbuffer(str)
			},
			// 紧急暂停
			stopmodalFn() {
				this.stopFn()
				// this.stopIF = true
			},
			cinfstopIFIF() {
				this.stopFn()
				this.stopIF = false
			},
			stopstopIFIF() {
				this.stopIF = false
			},
			// 紧急暂停
			stopFn() {
				let xstop = ['0x01', '0x06', '0x20', '0x0E', '0x00', '0x07', '0xA2', '0x0B']
				let ystop = ['0x02', '0x06', '0x00', '0x4D', '0x00', '0x00', '0x19', '0xEE']
				this.conbuffer(xstop)
				setTimeout(() => {
					this.conbuffer(ystop)
				}, 500)
			},
			// 横向归零
			xWalkFn() {
				let lrstr = '00000000'
				let str = '0110208A000408' + lrstr + lrstr
				// crc
				let strcrc = str + this.crc16(str)[1] + this.crc16(str)[0]
				let arr = this.chunkStringByTwo(strcrc)
				let newarr = this.ocstr(arr)
				this.conbuffer(newarr)
				setTimeout(() => {
					this.qidongFn()
				}, 500)
			},
			// 纵向归零 
			yWalkFn() {
				let lrstr = '00000000'
				let str = '02100050000204' + lrstr
				// crc
				let strcrc = str + this.crc16(str)[1] + this.crc16(str)[0]
				let arr = this.chunkStringByTwo(strcrc)
				let newarr = this.ocstr(arr)
				this.conbuffer(newarr)
			},
			// 初始化
			iniIFFn() {
				// if (this.vuex_devicename == '') {
				// 	uni.showToast({
				// 		title: '蓝牙未连接',
				// 		duration: 2000
				// 	});
				// 	return
				// }
				this.infIF = true
			},

			// 初始化电机确定
			cinfconfirmIF() {
				this.infIF = false
				this.iniFn()
			},
			// 初始化电机取消
			infcancelIF() {
				this.infIF = false
			},
			//初始化电机
			iniFn() {
				this.inidev = false
				let abpos = ['0x01', '0x06', '0x20', '0x0D', '0x00', '0x02', '0x92', '0x08']
				let wpos = ['0x01', '0x06', '0x20', '0x0E', '0x00', '0x08', '0xE2', '0x0F']
				let hpos = ['0x02', '0x06', '0x00', '0x00', '0x00', '0x01', '0x48', '0x39']
				this.conbuffer(abpos)
				setTimeout(() => {
					this.conbuffer(wpos)
				}, 300)
				setTimeout(() => {
					this.conbuffer(hpos)
				}, 600)
			},
			// 点击横向按钮
			cexianBUTT(e, index) {
				// if (this.inidev) {
				// 	uni.showToast({
				// 		title: '设备未初始化',
				// 		mask: true,
				// 		duration: 1500
				// 	});
				// 	return
				// }
				this.cezhanObj.cexianlist[index].color = '#dc4b4b'
				let nub = (e.cR * 102 * 100).toFixed(0)
				let hex = this.decimalToHex(nub)
				
				// 负数
				if(nub<0){
					let numbnew = this.NumberOf1(nub)
					let hex16 = this.binaryToHex(numbnew)
				}
				// 正数
				let lrstr = this.strRepair(hex16, 8)
				let str = '0110208A000408' + lrstr + lrstr
				// crc
				let strcrc = str + this.crc16(str)[1] + this.crc16(str)[0]
				let arr = this.chunkStringByTwo(strcrc)
				let newarr = this.ocstr(arr)
				this.conbuffer(newarr)
				setTimeout(() => {
					this.qidongFn()
				}, 500)
			},
			// 启动
			qidongFn() {
				let ble = ['0x01', '0x06', '0x20', '0x0E', '0x00', '0x10', '0xE2', '0x05']
				this.conbuffer(ble)
			},
			//询问水深
			inwaterFn() {
				// if (this.inidev) {
				// 	uni.showToast({
				// 		title: '设备未初始化',
				// 		mask: true,
				// 		duration: 1500
				// 	});
				// 	return
				// }
				this.depthWater.length = 0
				// this.pointerWater = 'none' //禁止点击设备入水
				setTimeout(() => {
					this.pointerWater = 'auto' //设备入水
				}, 100000)
				let arr = ['0x03', '0x03', '0x00', '0x02', '0x00', '0x01', '0x24', '0x28']
				for (let i = 0; i < 10; i++) {
					setTimeout(() => {
						this.conbuffer(arr)
					}, i * 500)
				}

			},
			// 处理水深
			treatmentDepth(data) {
				this.wD = data / 100
				let domStr = this.cezhanObj.installH * 1 - this.hexToDecimal(str) / 100 +
					this
					.cezhanObj.thoroughH * 1
				this.declineFn(domStr)
			},
			// 设备下降
			declineFn(numbdata) {
				let data = numbdata.toFixed(2) * 1
				let nub = (data * 20000 * 100 / 3).toFixed(0) * 1
				let numbnew = this.NumberOf1(-nub)
				let hex16 = this.binaryToHex(numbnew)
				let lrstr = this.strRepair(hex16, 8)
				let str = '02100050000204' + lrstr
				// crc
				let strcrc = str + this.crc16(str)[1] + this.crc16(str)[0]
				let arr = this.chunkStringByTwo(strcrc)
				let newarr = this.ocstr(arr)
				this.conbuffer(newarr)
			},
			//开始测流
			inquiryFn() {
				// if (this.inidev) {
				// 	uni.showToast({
				// 		title: '设备未初始化',
				// 		mask: true,
				// 		duration: 1500
				// 	});
				// 	return
				// }
				if (this.cezhanObj.cexianlist.length == 0) {
					uni.showToast({
						title: '未选择测线',
						mask: true,
						duration: 1500
					});
					return
				}
				if (this.sumArr.length >= this.cezhanObj.cexianlist.length && this.cezhanObj.cexianlist.length == 0) {
					uni.showToast({
						title: '已无测线数据',
						mask: true,
						duration: 1500
					});
					return
				}
				if (this.sumArr.length == this.cezhanObj.cexianlist.length && this.cezhanObj.cexianlist.length != 0) {
					uni.showToast({
						title: '测量完成',
						mask: true,
						duration: 1500
					});
					return
				}
				this.mfvNumArr = [] //数组100
				this.sumIfArr = true //数组求和平均判断
				// this.pointerMeasure = 'none' //禁止点击测量
				// this.pointerWater = 'none' //禁止点击设备入水
				let arr = ['0x04', '0x04', '0x00', '0x00', '0x00', '0x04', '0xF1', '0x9C']
				this.continuityFn(arr)
			},
			// 持续获取设备流速
			continuityFn(data) {
				// 图表
				this.objCLC.categories = []
				this.objCLC.series[0].data = []
				this.mfvNumArr = []
				// 图表
				for (let i = 0; i < 210; i++) {
					this.$refs.myclc.onloshow()
					if (this.mfvNumArr.length <= 200) {
						setTimeout(() => {
							this.conbuffer(data)
							// 测试随机
							// let newnub = this.getRandomNumber(600,3000)
							// this.mfvFn(newnub)
							// 测试随机
						}, i * 500)
					}
				}
			},
			// 获取测流数据
			mfvFn(data) {
				let num = data.toFixed(3) / 1000
				if (this.mfvNumArr.length < 200) {
					this.mfvNumArr.push(num)
					this.timereal = num //实时数据
					// 测试图表
					this.objCLC.categories.push(num)
					this.objCLC.series[0].data.push(num)
					// 测试图表
					return
				}
				if (this.sumIfArr) {
					this.removeSmallestN(this.mfvNumArr, 50)
					this.removeMax(this.mfvNumArr, 50)
					console.log('88888', this.mfvNumArr, this.mfvNumArr.length);
					let sumnum = {
						aveTy: null
					}
					sumnum.aveTy = this.averageSum(this.mfvNumArr).toFixed(3) * 1
					this.sumArr.push(sumnum)
					this.sumIfArr = false //执行一次
					this.pointerMeasure = 'auto' //允许点击测量
					// this.pointerWater = 'auto' //允许点击设备下水
					this.riseFn() // 水面提升
					console.log(this.sumArr.length);
					this.calculateFlow(this.sumArr)
				}
			},
			// 设备上升
			riseFn() {
				let domStr = this.cezhanObj.installH * 1 - this.wD - this.cezhanObj.waterH * 1
				this.declineFn(domStr)
			},
			// 计算流量
			calculateFlow(dataArr) {
				if (this.wD <= 0) {
					uni.showToast({
						icon: 'fail',
						title: '未获取水深',
						duration: 1500
					});
					return
				}
				let vls = dataArr
				let vlAll = []
				let vl0 = null //区域流量
				let vl1 = null //区域流量
				let vlz = null //区域流量
				let vln = null //区域流量
				let vln1 = null //区域流量
				let vln2 = null //区域流量

				// 不参与循环
				// cot
				let sin27LL = Math.sin(this.cezhanObj.lSA * Math.PI / 180)
				let cos27LL = Math.cos(this.cezhanObj.lSA * Math.PI / 180)
				let areaLL = cos27LL / sin27LL //三角面积L

				let sin27RR = Math.sin(this.cezhanObj.rSA * Math.PI / 180)
				let cos27RR = Math.cos(this.cezhanObj.rSA * Math.PI / 180)
				let areaRR = cos27RR / sin27RR //三角面积R
				// VL0
				vl0 = 0.5 * this.wD * this.wD * areaLL * (vls[0].aveTy * 1) * (this
					.cezhanObj.vmL * 1) * (this.cezhanObj.kL * 1)
				vlAll.push(vl0.toFixed(6) * 1)

				//VL1
				vl1 = 0.5 * [(vls[0].aveTy * 1) * (this.cezhanObj.vmL * 1) + (vls[0].aveTy * 1) * (this.cezhanObj
					.cexianlist[0].vM * 1)] * (this.wD) * (this.cezhanObj.cexianlist[0].cR * 1)
				vlAll.push(vl1.toFixed(6) * 1)


				// 中间逻辑
				if (vls.length > 1) {
					for (let i = 0; i < vls.length - 1; i++) {
						vlz = 0.5 * [(vls[i].aveTy * 1) * (this.cezhanObj.cexianlist[i].vM * 1) + (vls[i + 1].aveTy * 1) *
							(this.cezhanObj.cexianlist[i + 1].vM * 1)
						] * (this.wD) * [(this.cezhanObj.cexianlist[i + 1].cR * 1) - (this.cezhanObj.cexianlist[i].cR *
							1)]
						vlAll.push(vlz.toFixed(6) * 1)
					}
				}


				//VLN+1
				vln1 = 0.5 * [(vls[vls.length - 1].aveTy * 1) * (this.cezhanObj.vmR) + (vls[vls.length - 1]
					.aveTy * 1) * (this.cezhanObj.cexianlist[vls.length - 1].vM * 1)] * (this.wD) * [(this
					.cezhanObj.qudikuandu * 1) - (this.cezhanObj.cexianlist[vls.length - 1].cR * 1)]
				vlAll.push(vln1.toFixed(6) * 1)


				//VLN+2
				vln2 = 0.5 * this.wD * this.wD * areaRR * (vls[vls.length - 1].aveTy * 1) * (this
					.cezhanObj.vmR * 1) * (this.cezhanObj.kR * 1)
				vlAll.push(vln2.toFixed(6) * 1)
				// 计算总平均流速
				let vlQitem = []
				let vlQArr = []
				let vlQALL = []

				let sum = 0;
				for (let i = 0; i < vlAll.length; i++) {
					sum += vlAll[i];
				}
				this.liusliangnub = sum.toFixed(4) * 1
				if (this.sumArr.length == this.cezhanObj.cexianlist.length && this.cezhanObj.cexianlist.length != 0) {
					uni.showToast({
						title: '测量完成',
						mask: true,
						duration: 1500
					});
					this.disabledIf = false
					return
				}
			},
			// 配置
			allocationFn() {
				this.showpop = true
			},
			// 流速历史记录
			flowHistoryFn() {
				this.flowHistorypop = true
				this.Arrflow = this.vuex_flowHistory
			},
			confirmHistoryFn() {
				this.flowHistorypop = false
			},
			// 确认
			confirmFn() {
				this.showpop = false
			},
			// 取消
			cancelFn() {
				this.showpop = false
			},
			//弹窗配置
			//下拉框
			changesel(e) {
				let arr = []
				for (let i = 0; i < e; i++) {
					let obj = {
						cR: '',
						vM: '1',
						color: "#0090d8"
					}
					arr.push(obj)
				}
				this.cezhanObj.cexianlist = arr
				
			},
			// 返回
			retFn() {
				this.showIF = true
			},
			// 是否返回
			confirmIF() {
				uni.navigateBack({
					delta: 1
				});
				this.showIF = false
			},
			cancelIF() {
				this.showIF = false
			},
			// 长按删除
			onLongPress(e) {
				this.deleteId = e.id
				this.showHistoryIF = true
			},
			// 查询历史
			flowCheckpopFn(e) {
				this.flowCheckpop = true
				this.letviewHistory = e
			},
			confirmflowCheckpopFn() {
				this.flowCheckpop = false
			},
			// 是否删除
			confirmHistoryIF() {
				this.showHistoryIF = false
				let arr = this.removeById(this.Arrflow, this.deleteId)
				uni.$u.vuex('vuex_flowHistory', arr)
				this.Arrflow = this.vuex_flowHistory
			},
			cancelHistoryIF() {
				this.showHistoryIF = false
			},
			// 保存流量
			preserveFn() {
				let day = dayjs(new Date()).format('YYYY-MM-DD HH:mm')
				let arr = this.vuex_flowHistory
				let obj = {
					id: this.nanoid(),
					time: day,
					sumArr: this.sumArr,
					liusliangnub: this.liusliangnub,
					wD: this.wD
				}
				arr.push(obj)
				uni.$u.vuex('vuex_flowHistory', arr)
				// 清空
				this.delallFn()
				// 坐标归零
				this.zeroingFn()
			},
			// 输入蓝牙数据
			conbuffer(data) {
				let msg = data
				// 向蓝牙设备发送一个0x00的16进制数据
				const buffer = new ArrayBuffer(msg.length)
				const dataView = new DataView(buffer)
				// dataView.setUint8(0, 0)
				for (var i = 0; i < msg.length; i++) {
					// dataView.setUint8(i, msg.charAt(i).charCodeAt())
					dataView.setUint8(i, msg[i]);
				}
				this.sendMsgToKey(buffer)
			},
			//监听消息变化
			listenValueChange(data) {
				let resHex = data
				setTimeout(() => {
					uni.onBLECharacteristicValueChange(res => {
						let resHex = this.ab2hex(res.value)
						console.log('监听初始化数据', resHex, resHex.length);
						// 询问水深
						if (resHex.substr(0, 6) == '030302' && resHex.length == 14) {
							let str = resHex.substr(6, 4)
							let nubm = this.hexToDecimal(str)
							this.depthWater.push(nubm)
							this.wD = nubm / 100
							if (this.depthWater.length == 10) {
								let arr = this.depthWater
								this.removeSmallestN(arr, 5)
								this.removeMax(arr, 4)
								this.treatmentDepth(arr[0])
							}
						}
						// 获取流速
						if (resHex.substr(0, 6) == '040408' && resHex.length == 26) {
							let str = resHex.substr(14, 4)
							this.mfvFn(this.hexToDecimal(str))
						}
					})
				}, 300)
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.vuex_deviceId,
						success: (res) => {
							console.log('获取蓝牙所有服务', res);
							//E95D93AF-251D-470A-A062-FA1922DFA9A8
							//6E400001-B5A3-F393-E0A9-E50E24DCCA9E
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log('获取蓝牙特征值');
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {

							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {

								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("0000FFE1") != -1) {

									this.characteristicId = item.uuid
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								if (item.uuid.indexOf("0000FFF1") != -1) {

									this.characteristicId = item.uuid


									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 10进制转32位二进制补码
			NumberOf1(num) {
				// 获取负数的绝对值
				const absoluteValue = Math.abs(num);

				// 将绝对值转换为32位二进制字符串
				let binaryString = absoluteValue.toString(2);

				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				// 对二进制字符串取反
				const invertedBinaryString = binaryString.split('').map(bit => bit === '0' ? '1' : '0').join('');

				// 将取反后的二进制字符串转换为数字并加1
				const twosComplement = parseInt(invertedBinaryString, 2) + 1;

				// 再次将补码转换为32位二进制字符串
				binaryString = twosComplement.toString(2);

				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				return binaryString;
			},
			// 二进制补码转16进制
			binaryToHex(binaryStr) {
				// 确保二进制字符串是32位
				if (binaryStr.length !== 32) {
					throw new Error('Binary string must be 32 bits long');
				}

				// 将二进制字符串转换为数字
				var number = parseInt(binaryStr, 2);

				// 转换为16进制并返回结果
				return number.toString(16);
				// 示例使用
				// var binaryStr = '010101010101010101010101010101010'; // 32位二进制补码
				// var hexStr = binaryToHex(binaryStr);
			},
			//数组求平均
			averageSum(arr) {
				if (arr.length === 0) {
					return 0; // 当数组为空时，平均值为0
				}

				let sum = 0;
				for (let i = 0; i < arr.length; i++) {
					sum += arr[i];
				}

				return sum / arr.length;
			},
			// 长度不够补0
			strRepair(str, nub) {
				let nubm = nub * 1
				let strif = str + ''
				if (strif.length < nubm) {
					for (let i = 0; i < nubm - str.length; i++) {
						strif = '0' + strif
					}
				}
				return strif
			},
			//给每个数组添加0x
			ocstr(data) {
				let arr = []
				for (let i = 0; i < data.length; i++) {
					data[i] = '0x' + data[i]
				}
				return data
			},
			// 每2个字符串为一个元素数组
			chunkStringByTwo(str) {
				const result = [];
				for (let i = 0; i < str.length; i += 2) {
					result.push(str.slice(i, i + 2));
				}
				return result;
			},
			// 处理ASCLL 30 -00
			ascllFn(data) {
				let str = data + ''
				let arr = this.chunkStringByTwo(str)

				for (let i = 0; i < arr.length; i++) {
					if (arr[i] == '00') {
						arr[i] = '30'
					}
				}
				let arrnew = arr

				let strnre = ''
				for (let i = 0; i < arrnew.length; i++) {
					strnre += arrnew[i]
				}
				return strnre
			},
			// CRC16校验
			crc16(dataHexString) {
				const dataBytes = [];
				for (let i = 0; i < dataHexString.length; i += 2) {
					dataBytes.push(parseInt(dataHexString.substr(i, 2), 16));
				}

				let crc = 0xFFFF;
				const polynomial = 0xA001;

				for (const byte of dataBytes) {
					crc ^= byte;
					for (let i = 0; i < 8; i++) {
						if (crc & 0x0001) {
							crc = ((crc >> 1) ^ polynomial) & 0xFFFF;
						} else {
							crc >>= 1;
						}
					}
				}
				let crcstr = crc.toString(16).toUpperCase();
				if (crcstr.length % 2 == 0) {
					let result = crcstr.match(/.{1,2}/g)
					return result;
				} else {
					let str = '0' + crcstr
					let result = str.match(/.{1,2}/g)
					return result;
				}
			},
			// 16进制转10进制
			hexToDecimal(hex) {
				return parseInt(hex, 16);
			},
			// 10进制转16进制
			decimalToHex(data) {
				let decimal = data * 1
				let hex = decimal.toString(16).toUpperCase();3
				if (hex.length % 2 !== 0) {
					return '0' + hex
				} else {
					return hex
				}
				// return decimal.toString(16).toUpperCase();
			},
			// 16进制转字符串 ASCII码
			hexToString(hex) {
				let str = '';
				for (let i = 0; i < hex.length; i += 2) {
					let charCode = parseInt(hex.substr(i, 2), 16);
					str += String.fromCharCode(charCode);
				}
				return str;
			},

			//字符串转16进制
			stringToHex(data) {
				let str = data + ''
				return str.split('').map(function(char) {
					return char.charCodeAt(0).toString(16).padStart(2, '0');
				}).join('');
			},
			// 16进制转汉字
			hexToChinese(hex) {
				var str = '';
				for (var i = 0; i < hex.length / 4; i++) {
					var codePoint = parseInt(hex.substr(i * 4, 4), 16); // 获取每四位的十六进制值并转换成十进制
					str += String.fromCharCode(codePoint); // 根据Unicode编码生成对应的字符
				}
				return str;
			},
			// 汉字转16进制
			convertToHex(str) {
				let result = '';
				for (let i = 0; i < str.length; i++) {
					result += str.charCodeAt(i).toString(16);
				}
				return result;
			},
			// 随机数
			getRandomNumber(min, max) {
				return Math.floor(Math.random() * (max - min + 1)) + min;
			},
			// 删除最小的前面几个数字
			removeSmallestN(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最前面的n个数字
				sorted.splice(0, n);
				return sorted;
			},
			// 删除最大的后面几个数字
			removeMax(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最后面的n个数字
				sorted.splice(-n);
				return sorted;
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			/* 向设备发送消息(分包发送，单包20字节，递归发送)
			 */
			sendMsgToKey(buffer) {
				var that = this //vue中的this
				const packageSize = 20 //分包大小
				if (buffer.byteLength <= 20) { //如果小于20直接发送，不再继续调用
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buffer,
						writeType: 'write',
						success: (res) => {
							//此时设备已接收到你写入的数据
							console.log('写入111');

						},
						fail: (err) => {
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				} else { //如果大于20发送完成后继续递归调用
					var newData = buffer.slice(20)
					var writeBuffer = buffer.slice(0, 20)
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: writeBuffer,
						writeType: 'write',
						success: function(res) {
							console.log('写入222');
							//写入后继续递归调用发送剩下的数据
							setTimeout(() => {
								that.sendMsgToKey(newData)
							}, 100)
						},
						fail: (err) => {
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				}
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				console.log('启用 notify 功能');
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,

					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('蓝牙名字', res);
						// vuex
						// uni.$u.vuex('vuex_devicename', this.vuexlist.name)
						uni.hideLoading()
						this.listenValueChange()
						uni.showToast({
							title: '服务已开启',
							mask: true,
							duration: 1000
						});
						console.log('蓝牙服务已开启');
					},
					fail: (res) => {
						uni.hideLoading()
						uni.showToast({
							title: '获取服务失败',
							icon: 'fail',
							mask: true,
							duration: 1000
						});

					}
				})
			},
			// 删除数组
			removeById(arr, id) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i].id === id) {
						arr.splice(i, 1);
						break;
					}
				}
				return arr;
			},
			// 生Id
			nanoid(size = 21) {
				let id = ''
				let i = size
				while (i--) {
					id += this.urlAlphabet[(Math.random() * 64) | 0]
				}
				return id
			}
		}
	}
</script>
<style scoped lang="scss">
	// 内容
	.concent_box {
		padding: 30rpx;

		.inibox {
			margin-bottom: 20rpx;

			.inibox_but {
				text-align: center;
				color: #515151;
				font-size: 30rpx;
				padding: 10rpx 0;
				border-radius: 200rpx;
				background-color: #f2f7f7;
				border: 10rpx solid #f2f7f7;
				box-shadow: inset 0 0 20rpx rgba(140, 140, 140, 0.4);
			}

			.inibox_acv {
				color: #ffffff;
				background-color: #d0d4d4;
			}
		}

		.butt_box {
			display: flex;
			// align-items: center;
			// justify-content: space-between;
			flex-wrap: wrap;

			.butt_i {
				width: 200rpx;
				margin: 15rpx;
			}
		}

		.yuan {
			display: flex;
			justify-content: space-around;
			align-items: center;

			.yuan_a1 {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin: 30rpx 0;
				width: 200rpx;
				height: 200rpx;
				color: #ffffff;
				font-size: 50rpx;
				border-radius: 200rpx;
				background-color: #3998d2;
				border: 25rpx solid #3998d2;
				box-shadow: inset 0 0 30rpx rgba(255, 255, 255, 0.4);

				.text {
					text-align: center;
				}
			}

			.yuan_a_av1 {
				background-color: #42b9ef;
				color: #10fbff;
			}

			.yuan_a2 {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin: 30rpx 0;
				width: 200rpx;
				height: 200rpx;
				color: #ffffff;
				font-size: 50rpx;
				border-radius: 200rpx;
				background-color: #f2c125;
				border: 25rpx solid #f2c125;
				box-shadow: inset 0 0 30rpx rgba(255, 255, 255, 0.6);


				.text {
					text-align: center;
				}
			}

			.yuan_a_av2 {
				background-color: #f7d936;
				color: #f1ff6a;
			}
		}

		.realtime {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			padding: 30rpx;
			margin: 20rpx 0;
			background-color: #fafafa;
			border-radius: 20rpx;
			border: 3rpx solid #fff;
			padding: 10rpx;
			box-shadow: 0 0 15rpx rgba(127, 127, 127, 0.2);

			.i_a {
				color: #304951;
			}

			.i_b {
				font-size: 70rpx;
				text-align: center;
				border-radius: 10rpx;
				width: 320rpx;
				font-family: 'MyFont';
				background-color: #304951;
				color: #33ff9e;
			}

			.i_c {
				margin-left: 20rpx;
				font-size: 40rpx;
			}
		}

		// 图表
		.ucharts_box {
			background-color: #000000;
		}

		.box_num {
			font-family: 'MyFont';
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-wrap: wrap;

			.num_i {
				width: 320rpx;
				margin: 10rpx 0;
				background-color: #fafafa;
				border-radius: 20rpx;
				border: 3rpx solid #fff;
				padding: 10rpx;
				box-shadow: 0 0 15rpx rgba(127, 127, 127, 0.2);

				.text_top {

					.text {
						// margin-bottom: 10rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.text_a {
							font-size: 30rpx;
							color: #8cafa8;
						}

						.text_b {
							color: #45fada;
							text-align: center;
							font-size: 40rpx;
							width: 160rpx;
							padding: 5rpx;
							border-radius: 10rpx;
							background-color: #304951;
						}
					}
				}

				.text_bom {
					text-align: center;
					color: #eeca74;
					font-size: 35rpx;
				}
			}
		}
	}

	// 历史记录
	.pop_istoryFn {
		width: 695rpx;
		height: 1200rpx;
		overflow: auto;
		padding: 100rpx 20rpx;

		.conpop {
			border-radius: 20rpx;
			padding: 20rpx;
			margin-bottom: 15rpx;
			border: 2rpx solid #fff;
			background-color: #f4f6f8;
			box-shadow: 0 0 10rpx #cbd4da;

			.popitem {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.l {
					margin-left: 20rpx;
					width: 200rpx;
				}

				.poptext {
					width: 250rpx;
					color: #213847;
					text-align: justify;
					text-align-last: justify;
				}

				.poptext_b {
					font-size: 40rpx;
					color: #209361;
				}

				.poptext_c {
					font-size: 50rpx;
					color: #209361;
					font-family: 'MyFont';
				}
			}
		}

		.butpop {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
		}
	}

	.viewHistory {
		width: 695rpx;
		height: 1200rpx;
		overflow: auto;
		padding: 100rpx 30rpx;

		.realtime {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			padding: 30rpx;
			margin: 20rpx 0;
			background-color: #fafafa;
			border-radius: 20rpx;
			border: 3rpx solid #fff;
			padding: 10rpx;
			box-shadow: 0 0 15rpx rgba(127, 127, 127, 0.2);

			.i_a {
				color: #304951;
			}

			.i_b {
				font-size: 70rpx;
				text-align: center;
				border-radius: 10rpx;
				width: 320rpx;
				font-family: 'MyFont';
				background-color: #304951;
				color: #33ff9e;
			}

			.i_c {
				margin-left: 20rpx;
				font-size: 40rpx;
			}
		}

		.box_num {
			font-family: 'MyFont';
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-wrap: wrap;

			.num_i {
				width: 320rpx;
				margin: 10rpx 0;
				background-color: #fafafa;
				border-radius: 20rpx;
				border: 3rpx solid #fff;
				padding: 10rpx;
				box-shadow: 0 0 15rpx rgba(127, 127, 127, 0.2);

				.text_top {

					.text {
						// margin-bottom: 10rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.text_a {
							font-size: 30rpx;
							color: #8cafa8;
						}

						.text_b {
							color: #45fada;
							text-align: center;
							font-size: 40rpx;
							width: 160rpx;
							padding: 5rpx;
							border-radius: 10rpx;
							background-color: #304951;
						}
					}
				}

				.text_bom {
					text-align: center;
					color: #eeca74;
					font-size: 35rpx;
				}
			}
		}
	}

	.butflx {
		padding: 20rpx;
		padding-bottom: 120rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.tophead {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 60rpx 20rpx 10rpx 20rpx;
		color: #000000;
		background-color: #ffffff;
	}

	.classpop {
		width: 600rpx;
		height: 1200rpx;
		overflow: auto;
		padding: 100rpx 50rpx;
		display: flex;
		flex-direction: column;

		.conpop {
			.popitem {
				margin-bottom: 10rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.l {
					margin-left: 20rpx;
					width: 200rpx;
				}

				.poptext {
					width: 250rpx;
					text-align: justify;
					text-align-last: justify;
				}
			}
		}

		.butpop {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
		}
	}

	// 紧急暂停
	.emergencySuspension {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx 0 20rpx;

		.butto {
			margin: 0 30rpx 0rpx 30rpx;
		}
	}
</style>
<style>
	@font-face {
		font-family: 'MyFont';
		src: url('@/static/fonts/LED.otf');
	}

	/* 	page {
		background-color: #ffffff;
	} */
</style>